/**
 * 数据过滤器
 *
 * Created by snowingsea on 2020/01/21.
 */

/**
 * 数据过滤
 * @param {Object} modelInstance 模型
 * @param {Number} page 指定页
 * @param {Number} perPage 每页的记录数
 * @param {String} sortBy 排序项
 * @param {String} order 排序顺序
 * @param {Number} skipIndex 分页自定义跳跃次数
 * @param {Object|Function} options 选项
 * @return {Promise}
 */
function filter(modelInstance, {
  page = 1,
  perPage = 20,
  sortBy = null,
  order = 'asc', // eslint-disable-line comma-dangle
  collation,
  useAggregate = false,
  skipIndex,
} = {}, options = {}, pipeline) {
  let exec = useAggregate ? modelInstance.aggregate().match(options).allowDiskUse(true) : modelInstance.find(options);
  if (collation) {
    exec = exec.collation(collation);
  }
  if (sortBy && order) {
    if (Array.isArray(order)) {
      // 按指定数组进行排序，此时必须使用aggregate
      if (!useAggregate) {
        throw new Error('should use aggregate when order is an array');
      }
      exec.addFields({ __sortWeight: { $indexOfArray: [order, `$${sortBy}`] } });
      exec.sort({
        __sortWeight: 1,
      });
      exec.append({ $unset: '__sortWeight' });
    } else {
      const sort = {};
      sort[sortBy] = order;
      // 二级排序根据时间倒序排
      if (sortBy !== '_id') {
        sort._id = -1;
      }
      exec = exec.sort(sort);
    }
  }
  if (perPage) {
    if (page) {
      exec = exec.skip(skipIndex || (page - 1) * perPage);
    }
    exec = exec.limit(perPage);
  }
  if (pipeline) {
    if (!useAggregate) {
      throw new Error('should use aggregate when use pipeline');
    }
    exec.append(pipeline);
  }
  return exec.exec();
}

/**
 * Export model definition object.
 */
module.exports = {
  filter,
};
